package com.cliff.joinme;

import org.cybergarage.upnp.Device;
import org.cybergarage.upnp.DeviceList;

import android.os.Bundle;
import android.widget.Toast;

import com.actionbarsherlock.app.SherlockActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.actionbarsherlock.view.SubMenu;
import com.androidquery.AQuery;
import com.cliff.joinme.toolkit.ControlPointManager;

public class SelectRendererActivity extends SherlockActivity {

	protected AQuery aq = null;
	protected SubMenu mSubMenuRenderer = null;
	protected boolean selectRendererSucceeded = false;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		aq = new AQuery(this);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		SubMenu subMenuRenderer = menu.addSubMenu(Constants.GROUP_NONE,
				Constants.ITEM_SELECT_RENDERER, 0, R.string.menu_renderer);
		mSubMenuRenderer = subMenuRenderer;

		MenuItem subMenuItemRenderer = subMenuRenderer.getItem();
		subMenuItemRenderer.setIcon(android.R.drawable.ic_menu_upload_you_tube);
		subMenuItemRenderer.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS
				| MenuItem.SHOW_AS_ACTION_WITH_TEXT);

		return true;
	}

	protected void updateSubMenuRenderer() {
		Device dev = null;
		int order = 0;

		mSubMenuRenderer.clear();
		mSubMenuRenderer.add(Constants.GROUP_RENDERER,
				Constants.ITEM_LOCAL_RENDERER, order, R.string.local_renderer);

		DeviceList devList = ControlPointManager.getInstance().getRendererList();
		int devCnt = devList.size();
		for (int n = 0; n < devCnt; n++) {
			dev = devList.getDevice(n);
			order++;
			mSubMenuRenderer.add(Constants.GROUP_RENDERER, n, order,
					ControlPointManager.getInstance().getRendererDisplayName(dev));
		}
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		int itemId = item.getItemId();
		int groupId = item.getGroupId();
		selectRendererSucceeded = false;

		if (Constants.GROUP_NONE == groupId) {
			switch (itemId) {
			case Constants.ITEM_SELECT_RENDERER:
				updateSubMenuRenderer();
			default:
				return super.onOptionsItemSelected(item);
			}
		}

		if (Constants.GROUP_RENDERER == groupId) {
			if (ControlPointManager.getInstance().selectRenderer(itemId))
				selectRendererSucceeded = true;
		}
		return true;
	}
	
	public void updateRendererDisplay() {
		Device renderer = ControlPointManager.getInstance().getSelectedRenderer();

		if (null == renderer)
			aq.id(R.id.TextViewRenderer).text(R.string.local_renderer);
		else {
			aq.id(R.id.TextViewRenderer).text(ControlPointManager.getInstance().getRendererDisplayName(renderer));
		}
    }
	
}
